#ifndef __RENDERERWORKER__
#define __RENDERERWORKER__

#include <wx\thread.h>
#include "PrimitiveRendererBase.h"
#include "RendererBase.h"
#include <queue>
#include "IReportProgress.h"

class RendererWorker : public wxThreadHelper, public IReportProgress
{
public:
	RendererBase			*Renderer;
	wxMutex					ChunksAccessLock;
	
	wxMutex					WorkerLock;
	wxCondition				WorkerCondition;

	wxMutex					WorkerCloseMutex;

	std::queue<Point2i>		ChunksToRender;
	byte					Percent;
	wxString				Status;
	bool					ShouldQuit;

	~RendererWorker()
	{
	}

	int _goal, _val;
	void SetProgressGoal(const int &goal, const wxString &status)
	{
		_goal = goal;
		Status = status;
		_val = 0;
		Percent = 0;
	}

	bool IncrementProgress()
	{
		Percent = (int)(((float)++_val / (float)_goal) * 100);
	
		return GetThread()->TestDestroy();
	}

	RendererWorker(RendererBase *renderer) :
		Renderer(renderer),
		wxThreadHelper(wxTHREAD_DETACHED),
		WorkerCondition(WorkerLock),
		Percent(100),
		Status("Waiting"),
		ShouldQuit(false)
	{
	}

	void Restart()
	{
		// I can't lock for ShouldQuit, else it won't
		// pick it up if you switch during a long operation.
		// I don't think this should be an issue for a primitive type
		// with only one bit...
		ShouldQuit = true;

		WorkerCondition.Broadcast();
		GetThread()->Delete();
		CreateThread();

		std::queue<Point2i>().swap(ChunksToRender);
		Status = "Waiting";
		Percent = 100;
		ShouldQuit = false;

		GetThread()->Run();
	}

	PrimitiveRendererBase *RenderChunk(const int &x, const int &z);
	void *Entry();
};

#else
class RendererWorker;
#endif